/*
 * Author:  Copyright (c) 2013 Toby
 * E-Mail:  smurffit@gmail.com
 * Web:     https://code.google.com/p/chrome-mfi-filter4kiva/
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, see <http://www.gnu.org/licenses/>.
 */

'use strict';

var checkboxSwitch, colorHiddenBtn;
var bg = chrome.extension.getBackgroundPage();
init();

function init()
{
	createCheckBoxFilter();
	createListFiltered();
}
function createCheckBoxFilter()
{
	checkboxSwitch = document.getElementById('state');
	checkboxSwitch.addEventListener('click', toggleFilterState);
	if (bg.config.block)
	{
		checkboxSwitch.setAttribute('checked', 'checked');
	}
}
function createListFiltered()
{
	var incoming = window.location.hash.substring(1);
	// return if nothing has been filtered
	if (incoming.length === 0)
	{
		return;
	}

	colorHiddenBtn = document.getElementById('colorHidden');
	colorHiddenBtn.removeAttribute('hidden');
	colorHiddenBtn.addEventListener('click', toggleHiddenState);
	if (bg.showsFiltered)
	{
		colorHiddenBtn.innerHTML = 'Hide filtered';
	}

	document.querySelector('#popup').innerHTML = mergeArray(incoming.split('#')).join('\n');
}

function toggleHiddenState()
{
	if (colorHiddenBtn.innerHTML === 'Hide filtered')
	{
		colorHiddenBtn.innerHTML = 'Show filtered';
		bg.toggleHiddenState(false);
	}
	else if (colorHiddenBtn.innerHTML === 'Show filtered')
	{
		colorHiddenBtn.innerHTML = 'Hide filtered';
		bg.toggleHiddenState(true);
	}
	init();
}

function toggleFilterState()
{
	bg.toggleFilterState(checkboxSwitch.checked);
	init();
}

function mergeArray(original)
{
	var merged = [];
	// make a copy of the input array
	var copy = original.slice(0);

	// first loop goes over every element
	for ( var i = 0, l = original.length; i < l; i++)
	{
		var myCount = 0;
		// loop over every element in the copy and see if it's the same
		for ( var w = 0, v = copy.length; w < v; w++)
		{
			if (original[i] == copy[w])
			{
				myCount++; // increase amount of times duplicate is found
				copy[w] = null; // sets item to undefined
			}
		}

		if (myCount > 0)
		{
			merged.push(myCount + 'x - ' + original[i] + '<br />');
		}
	}
	merged.sort(function(a, b)
	{
		return b.charAt(0) - a.charAt(0);
	});
	return merged;
}
